<template>
	<view class="mine-container">
		<fui-nav-bar custom>
			<view class="u-flex u-row-right u-p-l-35 u-p-r-35" style="width: 100%;">
				<view class="u-flex u-row-between">
					<!-- #ifdef APP-PLUS -->
						<view class="u-m-r-30" @click="loginByScan">
							<image src="/static/home/icon_scan.png" class="header-icon" mode=""></image>
						</view>
					<!-- #endif -->
					<view class="" @click="$mRouter.push({ route: '/pages/mine/shezhi' })" >
						<image src="/static/home/icon_shezhi.png" class="header-icon" mode=""></image>
					</view>
				</view>
			</view>
		</fui-nav-bar>
		<view class="u-flex user-box u-p-l-35 u-p-r-35 u-p-b-40" @click="$mRouter.push({ route: '/pages/mine/shezhi/profile' })">
			<view class="u-m-r-28">
				<fui-avatar :src="headImg" width="120" height="120"></fui-avatar>
			</view>
			<view class="u-flex-1">
				<view class="u-font-18" style="font-weight: bold;">{{ nickname }}</view>
			</view>
			<view class="erweima u-m-r-18" @click.stop="$mRouter.push({ route: '/pages/mine/userCode' })">
				<image src="/static/erweima.png" style="width: 38rpx;height: 38rpx;" mode=""></image>
			</view>
		</view>
		<view class="u-m-b-20 u-m-t-20">
			<fui-list >
				<fui-list-cell>
					<text>手机号</text>
					<text class="fui-text__explain">{{hidePhone(storeUser.phoneNumber)}}</text>
				</fui-list-cell>
				<fui-list-cell arrow=""  @click="toShiming" :bottomBorder="false">
					<view class="u-flex u-row-between u-flex-1">
						<text>实名认证</text>
						<text class="fui-text__explain">{{realNameStatus}}</text>
					</view>
				</fui-list-cell>
			</fui-list>
		</view>
		<fui-list >
			<fui-list-cell  @click="videoPlay()" :bottomBorder="false">
				<text class="u-font-30 u-theme-main u-font-bold" >操作指南</text>
			</fui-list-cell>
		</fui-list>
		<fui-list class="u-m-t-20"  :bottomBorder="false">
			<fui-list-cell :bottomBorder="false" v-if="shopList.length != 0" >
				<text class="u-font-32 u-font-bold">企业</text>
			</fui-list-cell>
			<fui-list-cell arrow v-for="(item,index) in shopList" :key="index" @click="setShop(item)">
				<view class="u-flex u-row-between u-flex-1">
					<text>{{item.name}}</text>
					<text :style="getState(item.state,'style')">{{getState(item.state,'text')}}</text>
				</view>
			</fui-list-cell>
			<fui-list-cell :bottomBorder="false" v-if="shopList.length != 0" @click="createShopFn()">
				<view class="u-flex">
					<image src="/static/common/jia.png" mode="" style="width:50rpx; height: 50rpx;"></image>
					<text class="u-font-32 u-font-bold u-m-l-20 u-theme-main">企业注册</text>
				</view>
			</fui-list-cell>
		</fui-list>
		<!-- 二维码显示 -->
		<u-modal v-model="erweimaShow" width="60%" :show-title="false" :show-confirm-button="false" :show-cancel-button="false" :mask-close-able="true">
			<view class="slot-content">
				<view class="u-text-center u-m-t-20">
					个人二维码
				</view>
				<img :src="erweima" style="width: 100%;" mode="" />
			</view>
		</u-modal>
		<!-- 选择去采购管理 还是销售管理 -->
		<u-action-sheet v-model="typeShow" :list="typeList" @click="toPage"></u-action-sheet>
		<!--页面加载动画-->
		<!-- <akLoading isFullScreen :active="loading"></akLoading> -->
		<!-- tabbar -->
		<fui-tabbar :tabBar="tabbar"  :isFixed="true" ></fui-tabbar>
		<!-- 店铺注册拒绝 -->
		<u-modal v-model="applyFaild" mask-close-able :content="rejectReason" :cancel-text="'重新申请'"  @cancel="resetApplyFn" :confirm-text="'删除'" @confirm="deleteShop" ></u-modal>
	</view>
</template>

<script>
	// import HeaderXiaoxi from '@/components/header-xiaoxi/index.vue'
	// import ClickLogin from '@/pages/login/clickLogin.vue'
	// import {hex_md5,hex_hmac_md5} from '@/utils/md5.js'
	import {useUserStore} from '@/store/user.js';
	import {useShopStore} from '@/store/shop.js';
	import { mapState } from 'pinia'
	export default {
		// components: { ClickLogin, HeaderXiaoxi },
		data() {
			return {
				controls:true,
				loading: true,
				titleStyle: {
					fontSize: '32rpx',
					fontWeight: 'bolder',
					color: this.textColor
				},
				shopList: [],
				typeShow: false,
				typeList: [
					{ id: 1, text: '采购管理' },
					{ id: 2, text: '销售管理' }
				],
				erweimaShow: false,
				erweima: '',
				cellTitleStyle: {
					fontSize: '30rpx'
				},
				chooseShopId:null,
				applyFaild:false,
				rejectReason:"",
				resetShopId:'',
				reloadKey:'reload-wo-tabbar-guid'
			}
		},
		computed:{
			...mapState(useUserStore, {
				nickname:'nickname',
				headImg:'headImg',
					isAuthRealName:'isAuthRealName',
					storeUser: 'user',
					tabbar:'tabbar',
					isApprovalIng:'isApprovalIng',
				  realNameStatus(store){
					  let text = '';
					  if(!store.isAuthRealName){
						  if(!store.isApprovalIng){
							  text = '未实名'
						  }else{
							  text = '正在审核中'
						  }
					  }else{
						  text = '已实名'
					  }
					  return text;
				  },
			})	
		},
		async onShow() {
			uni.hideTabBar()
			setTimeout(() => {
				this.loading = false
			}, 100)
			// 实名认证得才获取
			if (this.isAuthRealName) {
				// 获取该用户注册的店铺
				this.getShopList()
			}
			// if(this.$store.state.common.reloadTabbar['mine']){
			// 	this.reloadKey = this.$u.guid(16);
			// 	this.$store.commit('common/CLOSE_TABBAR_STATUS','mine');
			// }
		},
		async onLoad() {
			uni.hideTabBar()
			await this.$onLaunched;
			if (!this.hasLogin) {
				return
			}
			this.loading = false
			// 加载用户唯一二维码
			if (this.hasLogin) {
				this.getQrcode();
			}
			// 实名认证得才获取
			if (this.isAuthRealName) {
				// 获取该用户注册的店铺
				this.getShopList();
			}
		},
		methods: {
			// 店铺状态枚举
			getState(state,type) {
				let stateText = '';
				let stateStyle = {
					fontSize:"20rpx",
				};
				switch(state) {
					case 0:
						stateText = '审核中';
						stateStyle.color="#1A95EB";
						break;
					case 1:
						stateStyle.visibility="hidden";
						stateText = '已审核';
						break;
					case 4:
						stateText = '未通过';
						stateStyle.color="#999999";
						break;
					default:
						stateText = '审核中';
				}
				if(type == 'text'){
					return stateText
				}else{
					return stateStyle
				}
			},
			// 前往新手必看页面
			videoPlay(){
				this.$mRouter.push({ route: '/pages/mine/shezhi/operation' });
			},
			// 前往新赠企业页面
			createShopFn(){
				this.$mRouter.push({ route: '/pages/mine/createShop/index?type=add' });
			},
			// 扫码登录
			loginByScan(){
				let that = this;
				// this.toScanLogin()
				uni.scanCode({
					success: async (res) => {
						console.log(res);
						let signKey = '9B007D549195C034C9A1C3E46AE581A72BC9A54BEDC7E36EBEE2834B58C6BC85';
						let qrdata = res.result;
						let openId = that.storeUser.idsOpenId
						let option = {
							qrdata:res.result,
							openId:that.storeUser.idsOpenId,
							sign:hex_md5(`${qrdata}&${openId}&${signKey}`)
						} 
						await this.$nextTick();
						setTimeout(() => {
							that.toScanLogin(JSON.stringify(option));
						},800);
					},
					error:(Error)=>{
						console.log(Error);
					}
				});
			},
			// 获取二维码
			async getQrcode() {
				const res = await this.$http.get('api/User/QRCodeGenerate/QRCode.png', { responseType: 'arraybuffer'})
				this.erweima = 'data:image/jpeg;base64,'+ uni.arrayBufferToBase64(res)
			},
			// 保存二维码到本地
			saveLocationFn(){
				let base64 = this.erweima;
				 const bitmap = new plus.nativeObj.Bitmap("test");
				     bitmap.loadBase64Data(base64, function() {
				         const url = "_doc/" + new Date().getTime() + ".png";  // url为时间戳命名方式
				         console.log('saveHeadImgFile', url)
				         bitmap.save(url, {
				             overwrite: true,  // 是否覆盖
				             // quality: 'quality'  // 图片清晰度
				         }, (i) => {
				             uni.saveImageToPhotosAlbum({
				                 filePath: url,
				                 success: function() {
				                     uni.showToast({
				                         title: '图片保存成功',
				                         icon: 'none'
				                     })
				                     bitmap.clear()
				                 }
				             });
				         }, (e) => {
				             uni.showToast({
				                 title: '图片保存失败',
				                 icon: 'none'
				             })
				             bitmap.clear()
				         });
				     }, (e) => {
				         uni.showToast({
				             title: '图片保存失败',
				             icon: 'none'
				         })
				         bitmap.clear()
				}); 
			},
			// 获取店铺列表
			async getShopList() {
				const res = await this.$http.get('api/User/GetShopsByUser', { params: { id: this.storeUser.id, isManager: true } })
				this.shopList = res;
				console.log(res);
			},
			// 点击前往企业设置
			async setShop(item) {
				if(item.state ==4){
					this.applyFaild = true;
					this.resetShopId = item.id;
					const res = await this.$http.get('api/Shop/GetSignupInfo', { params: { shopId: item.id} });
					console.log(res);
					this.rejectReason = (res.rejectReason==''||!res.rejectReason)?'拒绝原因：'+'无':'拒绝原因：'+res.rejectReason;
					return;
				}
				if(item.state!=1&&item.state !=4){
					this.$mRouter.push({ route: '/pages/mine/createShop/index?id='+item.id+'&type=edit' });
					return;
				}
				this.$mRouter.push({ route: '/pages/mine/shopSet?id='+item.id+'&type=other' });
			},
			resetApplyFn(){
				this.$mRouter.push({ route: '/pages/mine/createShop/index?id='+this.resetShopId+'&type=edit' });
			},
			async deleteShop(){
				const res = await this.$newHttp.delete('api/v1.2/Shop/DeleteFailedApplications?shopId='+this.resetShopId);
				if(res.code === 200){
					this.getShopList();
				}else{
					this.$u.toast('删除店铺失败')
				}
			},
			// 隐藏手机中间四位
			hidePhone(val) {
				if (val) {
					return val.substr(0, 3) + '****' + val.substr(7)
				} else {
					return ''
				}
			},
			// 前往实名认证页
			toShiming() {
				if (this.realPeopleConfirmed) {
					return this.$u.toast('已实名');
				}
				if (!this.realPeopleConfirmed&&this.isApprovalIng) {
					return this.$u.toast('正在加急审核中，请耐心等待~');
				}
				this.$mRouter.push({ route: '/pages/mine/shezhi/shiming' });
			},
			// 采购还是销售 设置页选择
			toPage(index) {
				if (index == 1) {
					this.$mRouter.push({ route: '/pages/sale/shezhi/index?id='+this.chooseShopId+'&type=other'})
				} else {
					this.$mRouter.push({ route: '/pages/purchase/shezhi?id='+this.chooseShopId+'&type=other' })
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.mine-container{
		// height: 100%;
		background-color: #F8F8F8;
		box-sizing: border-box;
		padding-bottom: 160rpx;
	}
	// @import "@/static/iconfont/iconfont.css";
.camera{
	// width: 54px;
	// height: 44px;

	&:active{
		background-color: #ededed;
	}
}
.erweima {
	width: 38rpx;
	height: 38rpx;
	
	&:active {
		background-color: #ededed;
	}
}
.user-box{
	background-color: #fff;
}
</style>
